package runtime.demo3.handler;

import runtime.demo3.annotation.Constraints;
import runtime.demo3.annotation.DBTable;
import runtime.demo3.annotation.SQLInteger;
import runtime.demo3.annotation.SQLString;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * @Title: TableCreator
 * @Description: (运行时注解处理器 ， 构造表创建语句)
 * @return:
 */
public class TableCreator {

    public static String createTableSql(String className) throws ClassNotFoundException {
        Class<?> cl = Class.forName(className);
        DBTable dbTable = cl.getAnnotation(DBTable.class);
        if(dbTable == null) {
            System.out.println("No DBTable in class " + className);
            return null;
        }

        String tableName = dbTable.name();

        if(tableName.length() < 1)
            tableName = cl.getName().toUpperCase();

        ArrayList<String> columnDefs = new ArrayList<>();
        // 通过class类的API获取所有成员字段
        for(Field field : cl.getDeclaredFields()) {
            String columnName = null;
            // 获取字段上的注解
            Annotation[] anns = field.getDeclaredAnnotations();
            if(anns.length < 1)
                continue;

            // 判断Int注解类型
            if(anns[0] instanceof SQLInteger) {
                SQLInteger sInt = (SQLInteger) anns[0];
                // 获取字段对应的列名称，如果没有就使用字段名称代替
                if(sInt.name().length() < 1)
                    columnName = field.getName().toUpperCase();
                else
                    columnName = sInt.name();

                // 构建语句
                columnDefs.add(columnName + " INT" + getConstraints(sInt.constrain()));
            }

            // 判断String 注解类型
            if(anns[0] instanceof SQLString) {
                SQLString sString = (SQLString) anns[0];
                if(sString.name().length() < 1)
                    columnName = field.getName().toUpperCase();
                else
                    columnName = sString.name();

                columnDefs.add(columnName + " VARCHAR(" +
                    sString.value() + ")" +
                    getConstraints(sString.constrains()));
            }
        }

        // 数据库表构建语句
        StringBuilder createCommand = new StringBuilder(
                "CREATE TABLE " + tableName + "("
        );

        for(String columnDef : columnDefs)
            createCommand.append("\n    " + columnDef + ",");

        String tableCreate = createCommand.substring(0, createCommand.length()-1) + ");";

        return tableCreate;
    }

    /**
     * 判断该字段是否有其他约束
     * @param con
     * @return
     */
    private static String getConstraints(Constraints con) {
        String constraints = "";
        if(!con.allowNull())
            constraints += " NOT NULL";
        if(con.primaryKey())
            constraints += " PRIMARY KEY";
        if(con.unique())
            constraints += " UNIQUE";

        return constraints;
    }
}
